#include<pthread.h>
#include<iostream>
#include<unistd.h>

using namespace std;

pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;

const int num=5;//创建线程数量

void* Active(void* args)
{
    const char*name=static_cast<const char*>(args);

    while(true)
    {
        //加锁
        pthread_mutex_lock(&mtx);

        //等待条件变量
        pthread_cond_wait(&cond,&mtx);
        cout<<"线程:"<<name<<"正在运行"<<endl;

        //解锁
        pthread_mutex_unlock(&mtx);
    }

    delete[] name;
    return nullptr;
}

int main()
{
    pthread_t pt[num];
    for(int i=0;i<num;i++)
    {
        char *name=new char[64];
        snprintf(name,64,"thread-%d",i);
        pthread_create(pt+i,nullptr,Active,name);
    }

    sleep(3);


    while(true)
    {
        cout<<"Main thread wake up Other Thread"<<endl;
        pthread_cond_signal(&cond);
        sleep(1);
    }

    for(int i=0;i<num;i++)
    {
        pthread_join(pt[i],nullptr);
    }
    return 0;
}